// @login & register

const express = require('express')
const bcrypt = require('bcrypt')
const router = express.Router()
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const User = require('../../model/User')
const keys = require('../../config/key')
const passport = require('passport')

// @route GET api/users/test
// @desc 返回请求的json数据
// @access public(定义操作tooken的时候为private方法)
router.get('/test', (req, res) => {
  res.json({ msg: 'user login works' })
})

// @route POST api/users/register
// @desc 返回请求的json数据
// @access public
router.post('/register', (req, res) => {
  // console.log(req.body)
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json('email已被占用')
    } else {
      const avatar = gravatar.url(req.body.email, { s: '200', r: 'pg', d: 'mm' })
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        avatar,
        identity: req.body.identity
      })

      bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) {
            throw err
          }
          newUser.password = hash
          // 密码加密
          // 这一段必须在加密的function中执行,否则不生效
          console.log(newUser.password)
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err))
        })
      })
    }
  })
})

// @route POST api/users/login
// @desc 返回token jwt passport
// @access public(定义操作tooken的时候为private方法)
router.post('/login', (req, res) => {
  const email = req.body.email
  const password = req.body.password
  // 查询数据库
  User.findOne({ email }).then(user => {
    if (!user) {
      return res.status(404).json('用户不存在')
    }
    //密码匹配
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        // jwt.sign("规则","加密名字","过期时间{}","箭头函数");
        const rule = { id: user.id, name: user.name, avatar: user.avatar, identity: user.identity }

        jwt.sign(rule, keys.secretKey, { expiresIn: 3600 }, (err, token) => {
          if (err) throw err
          res.json({
            success: true,
            token: 'Bearer ' + token
          })
        })
        // return res.json({msg:"success"});
      } else {
        return res.status(400).json('密码错误!')
      }
    })
  })
})

// @route POST api/users/current
// @desc 返回 current user
// @access private
router.get('/current', passport.authenticate('jwt', { session: false }), (req, res) => {
  res.json({ id: req.user.id, name: req.user.name, email: req.user.email, identity: req.user.identity })
})

module.exports = router
